package juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test10 {
    public static void main(String[] args) {
        AirConditions airConditions = new AirConditions();

        new Thread(() -> {
            for (int i = 1; i <=30 ; i++) {
                try {
                    Thread.sleep(200);
                    airConditions.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(() -> {
            for (int i = 1; i <=30 ; i++) {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                airConditions.decrement();
            }
        },"B").start();

        new Thread(() -> {
            for (int i = 1; i <=30 ; i++) {
                try {
                    Thread.sleep(400);
                    airConditions.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(() -> {
            for (int i = 1; i <=30 ; i++) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                airConditions.decrement();
            }
        },"D").start();
    }
}
class AirConditions {

    private int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();


    public void increment() throws Exception {
        lock.lock();
        try {
            while (num != 0) {
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            while (num == 0) {
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName() + "\t" + num);
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            lock.unlock();
        }
    }

}